<template>
	<view class="cart-container">
		<!-- 空购物车显示 -->
		<view class="empty-cart" v-if="!cartList || cartList.length === 0">
			<image src="/static_package/images/car.png" mode="aspectFit" class="empty-icon"></image>
			<view class="empty-title">购物车竟然是空的</view>
			<view class="empty-desc">再忙，也要记得买点什么犒赏自己~</view>
			<button class="go-shopping-btn" @tap="goToHome">去首页逛逛</button>
		</view>

		<!-- 购物车列表 -->
		<view class="cart-content" v-if="cartList && cartList.length > 0">
			<!-- 有收货地址时显示 -->
			<view class="address-section" v-if="addressList?.length > 0 && selectedAddress && selectedAddress.id"
				@tap="handleAddressClick">
				<view class="img-box">
					<image src="/static/小货车.png" mode="aspectFit" class="img"></image>
				</view>
				<view class="address-info">
					<view class="address-top">
						<text class="address-title">{{ selectedAddress?.province || '' }} {{ selectedAddress?.city || ''
							}} {{
								selectedAddress?.country || '' }}</text>
						<text class="address-detail">{{ selectedAddress?.address || '' }}</text>
						<text class="name">{{ selectedAddress?.name || '' }} {{ selectedAddress?.tel || '' }}</text>
					</view>
				</view>
			</view>
			<!-- 没有收货地址时显示 -->
			<view class="no-address-section" v-if="!selectedAddress?.id" @tap="handleAddressClick">
				<view class="img-box">
					<image src="/static/地址添加.png" mode="aspectFit" class="img"></image>
				</view>
				<view class="address-title">添加收货地址</view>
			</view>
			<!-- 装饰线 -->
			<view class="decoration-line"></view>

			<!-- 购物车商品列表 -->
			<view class="cart-list">
				<view class="cart-item" v-for="item in cartList" :key="item.id">
					<!-- 选择框 -->
					<view class="checkbox" @tap="handleCheckItem(item)">
						<image
							:src="item.selected ? '/static/images/cart-selected.png' : '/static/images/cart-unselected.png'"
							mode="aspectFit"></image>
					</view>
					<!-- 商品图片 -->
					<image class="goods-image" :src="item.thumb_path" mode="aspectFill"></image>
					<!-- 商品信息 -->
					<view class="goods-info">
						<view class="goods-name">{{ item.title }}</view>
						<view class="goods-price-section">
							<view class="price-wrap">
								<text class="price-symbol">¥</text>
								<text class="price">{{ item.sell_price }}</text>
							</view>
							<view class="quantity-control">
								<text class="minus" @tap="handleQuantityChange(item, -1)">-</text>
								<input type="number" class="number" :value="item.number"
									@blur="handleQuantityBlur(item, $event)" />
								<text class="plus" @tap="handleQuantityChange(item, 1)">+</text>
							</view>
							<view class="delete-btn" @tap="handleDelete(item)">删除</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 底部结算栏 -->
			<view class="cart-footer" v-if="cartList.length > 0">
				<view class="footer-left">
					<view class="select-all">
						<text>共{{ totalCount }}件商品</text>
					</view>
					<text class="total-info">合计：<text class="amount">¥{{ selectedTotalPrice }}</text></text>
				</view>
				<view class="checkout-btn" @tap="handleCheckout">
					去结算({{ selectedCount }})
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { reqUserAddressList } from '@/api/user';
import { reqCommitOrder } from '@/api/order';
import { useUserStore } from '@/store';
import { storeToRefs } from 'pinia';
import { useCartStore } from '@/store/modules/cart';
import moment from 'moment';


const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const cartStore = useCartStore();
const {
	cartList,
	totalCount,
	selectedTotalPrice,
	selectedCount,
	temporaryAddress
} = storeToRefs(cartStore);

// 选中的地址
const selectedAddress = ref({});
const addressList = ref([]);


// 檢查登錄並跳轉
const checkLoginAndRedirect = () => {
	if (!userInfo.value.username) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		});
		// 使用switchTab跳转到首页
		uni.switchTab({
			url: '/pages/index/index'
		});
		// 延迟跳转到登录页，确保先完成switchTab
		setTimeout(() => {
			uni.navigateTo({
				url: '/pages/user_package/login/login?from=cart'
			});
		}, 100);
		return false;
	}
	return true;
};

// 处理商品选中状态
const handleCheckItem = (item) => {
	cartStore.toggleItemSelected(item.id);
};

// 处理数量变更
const handleQuantityChange = (item, change) => {
	//通知store更新购物车数量
	cartStore.updateCartItemNumber(item.id, item.number + change);
};

// 处理删除商品
const handleDelete = (item) => {
	uni.showModal({
		title: '提示',
		content: '确定要删除这个商品吗？',
		success: (res) => {
			if (res.confirm) {
				cartStore.removeFromCart(item.id);
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				});
			}
		}
	});
};

// 获取用户地址列表
const getAddressList = async () => {
	if (!userInfo.value.username) return;

	try {
		if (temporaryAddress.value) {
			selectedAddress.value = temporaryAddress.value;
			addressList.value = [temporaryAddress.value];
		} else {
			// 从服务器获取地址列表
			const res = await reqUserAddressList();
			addressList.value = res || [];
			if (res && res.length > 0) {
				const defaultAddress = res.find(item => item.isDefault) || res[0];
				selectedAddress.value = defaultAddress;
				uni.setStorageSync('temporaryAddress', defaultAddress);
			} else {
				selectedAddress.value = {}; // 确保为空对象而不是undefined
			}
		}
	} catch (error) {
		console.error('获取地址列表失败:', error);
		addressList.value = [];
		selectedAddress.value = {}; // 确保为空对象而不是undefined
	}
};

// 处理地址点击
const handleAddressClick = () => {
	if (!checkLoginAndRedirect()) return;

	// 跳转到地址列表页面
	uni.navigateTo({
		url: '/pages/address_package/address/address?from=cart'
	});
};

// 页面加载时检查登录状态
onLoad(() => {
	getAddressList();
});

// 页面显示时检查登录状态
onShow(() => {
	if (checkLoginAndRedirect()) {
		getAddressList();
	}
});

// 处理结算
const handleCheckout = async () => {
	if (!checkLoginAndRedirect()) return;

	if (cartStore.selectedCount === 0) {
		uni.showToast({
			title: '请选择要结算的商品',
			icon: 'none'
		});
		return;
	}

	if (!selectedAddress.value || !selectedAddress.value.id) {
		uni.showToast({
			title: '请选择收货地址',
			icon: 'none'
		});
		return;
	}
	//生成订单
	// 2. 下单,准备订单参数
	let orderData = {
		order_id: genOrderId(),//订单id
		address_id: selectedAddress.value.id,//收货地址id
		total_price: selectedTotalPrice.value,//订单总价
		number: selectedCount.value,//购买数量
		goods_ids: cartList.value.map(item => item.id).join(','),//把购物车中的商品id转换为字符串
	}
	let res = await reqCommitOrder(orderData)
	if (res.code === 20000) {
		uni.showToast({
			title: '生成订单成功',
			icon: 'success'
		});
		// 1. 清空购物车
		cartStore.clearCart()
		// 2. 进入到订单详情页面
		uni.navigateTo({
			url: '/pages/order_package/order/orderdetail?order_id=' + orderData.order_id
		});
	}
};
// 生成订单id
const genOrderId = () => {
	// 生成6位随机数
	let randomStr = ''
	for (let i = 1; i <= 6; i++) {
		randomStr += Math.floor(Math.random() * 10)
	}
	return moment().format('YYYYMMDDHHmmss') + randomStr
}

// 跳转到首页
const goToHome = () => {
	uni.switchTab({
		url: '/pages/index/index'
	});
};
</script>

<style lang="scss" scoped>
.cart-container {
	min-height: 100vh;
	background-color: #f8f8f8;
	position: relative;
	padding-bottom: 120rpx;

	.empty-cart {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-top: 200rpx;

		.empty-icon {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 40rpx;
		}

		.empty-title {
			font-size: 36rpx;
			color: #333333;
			font-weight: bold;
			margin-bottom: 20rpx;
		}

		.empty-desc {
			font-size: 28rpx;
			color: #999999;
			margin-bottom: 60rpx;
		}

		.go-shopping-btn {
			width: 240rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background: linear-gradient(135deg, #ff6b00, #ff8c00);
			color: #ffffff;
			border-radius: 40rpx;
			font-size: 28rpx;
			font-weight: 500;
			border: none;
			box-shadow: 0 4rpx 8rpx rgba(255, 107, 0, 0.2);

			&:active {
				transform: scale(0.98);
			}
		}
	}

	.address-section {
		display: flex;
		align-items: center;
		height: 180rpx;
		padding: 20rpx 30rpx;
		background: #fff;
		margin-bottom: 16rpx;

		.img-box {
			margin-right: 30rpx;

			.img {
				width: 50rpx;
				height: 50rpx;
			}

		}

		.address-info {
			.address-top {
				.address-title {
					font-size: 32rpx;
					color: #333;
					font-weight: 500;
					margin-bottom: 10rpx;
					display: block;
				}

				.address-detail {
					font-size: 28rpx;
					color: #666;
					margin-bottom: 10rpx;
					display: block;
				}

				.name {
					font-size: 28rpx;
					color: #666;
					display: block;
				}
			}
		}
	}

	.no-address-section {
		display: flex;
		align-items: center;
		height: 180rpx;
		padding: 20rpx 30rpx;
		background: #fff;
		margin-bottom: 16rpx;

		.img-box {
			margin-right: 30rpx;

			.img {
				width: 50rpx;
				height: 50rpx;
			}
		}

		.address-title {
			font-size: 28rpx;
			color: #151414;
			font-weight: 500;
			margin-bottom: 10rpx;
		}
	}

	.decoration-line {
		height: 6rpx;
		background: repeating-linear-gradient(to right,
				#ff6b6b 0rpx,
				#ff6b6b 20rpx,
				#4a90e2 20rpx,
				#4a90e2 40rpx);
	}

	.cart-list {
		background-color: #fff;
		padding: 20rpx;

		.cart-item {
			display: flex;
			padding: 20rpx;
			background: #fff;
			border-radius: 12rpx;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

			.checkbox {
				width: 40rpx;
				height: 40rpx;
				margin-right: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				align-self: center;

				image {
					width: 36rpx;
					height: 36rpx;
				}
			}

			.goods-image {
				width: 180rpx;
				height: 180rpx;
				margin-right: 20rpx;
				border-radius: 8rpx;
			}

			.goods-info {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.goods-name {
					font-size: 28rpx;
					color: #333;
					line-height: 1.4;
					margin-bottom: 20rpx;
				}

				.goods-price-section {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.price-wrap {
						display: flex;
						align-items: baseline;

						.price-symbol {
							font-size: 24rpx;
							color: #ff4444;
							margin-right: 4rpx;
						}

						.price {
							font-size: 36rpx;
							color: #ff4444;
							font-weight: bold;
						}
					}

					.quantity-control {
						display: flex;
						align-items: center;
						margin: 0 20rpx;

						.minus,
						.plus {
							width: 60rpx;
							height: 60rpx;
							line-height: 56rpx;
							text-align: center;
							border: 2rpx solid #eee;
							color: #333;
							font-size: 40rpx;
							background: #f8f8f8;
						}

						.number {
							width: 80rpx;
							height: 60rpx;
							line-height: 60rpx;
							text-align: center;
							border-top: 2rpx solid #eee;
							border-bottom: 2rpx solid #eee;
							color: #333;
							font-size: 28rpx;
						}
					}

					.delete-btn {
						width: 100rpx;
						height: 60rpx;
						line-height: 60rpx;
						text-align: center;
						background-color: #ff4444;
						color: #fff;
						font-size: 28rpx;
					}
				}
			}
		}
	}

	// 底部结算栏
	.cart-footer {
		position: fixed;
		left: 0;
		right: 0;
		bottom: var(--window-bottom, 0);
		height: 100rpx;
		background-color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 99;

		.footer-left {
			flex: 1;
			display: flex;
			align-items: center;
			font-size: 28rpx;
			color: #333;

			.select-all {
				display: flex;
				align-items: center;

				image {
					width: 36rpx;
					height: 36rpx;
					margin-right: 10rpx;
				}

				text {
					font-size: 28rpx;
					color: #333;
				}
			}

			.total-info {
				margin-left: 30rpx;

				.amount {
					color: #ff4444;
					font-size: 28rpx;
					font-weight: bold;
					margin-left: 4rpx;
				}
			}
		}

		.checkout-btn {
			min-width: 180rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background-color: #ff4444;
			color: #ffffff;
			font-size: 28rpx;
			border-radius: 40rpx;
			padding: 0 40rpx;
		}
	}
}
</style>